package com.zscat.mallplus.utils;

import com.alibaba.fastjson.JSON;
import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.auth.COSCredentials;
import com.qcloud.cos.model.ObjectMetadata;
import com.qcloud.cos.model.PutObjectRequest;
import com.qcloud.cos.model.PutObjectResult;
import com.qcloud.cos.region.Region;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.Objects;
import java.util.UUID;

/**
 * @author Created by 谭健 on 2020/9/18. 星期五. 14:00.
 * © All Rights Reserved.
 */
public class COSUtils {


    public static void main(String[] args) {

        // 示例代码
        File localFile = new File("C:\\Users\\A-PC\\Desktop\\1.txt");

        try {
            // 返回文件地址
            String upload = upload(new FileInputStream(localFile), "1.txt");
            System.out.println(upload);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }


    private static final String SID = "AKIDShgkYMrgQ3Vh5FPOQDnizHJ6Sr0ypAMH";
    private static final String SK = "oNvCG6fwVnoa4KI5cuxkHOFzauDJAkHt";

    private static final COSCredentials cred = new BasicCOSCredentials(SID, SK);

    private static final Region region = new Region("ap-nanjing");
    private static final ClientConfig clientConfig = new ClientConfig(region);

    public static final String DOMAIN = "https://public-1301924604.cos.ap-nanjing.myqcloud.com/";

    /**
     * 传到 COS
     *
     * @param inputStream 输入流
     * @param key         文件名
     */
    public static String upload(InputStream inputStream, String key) {
        //  生成 cos 客户端。
        COSClient cosClient = new COSClient(cred, clientConfig);
        // 指定要上传到的存储桶
        String bucketName = "public-1301924604";
        // 指定要上传到 COS 上对象键
        if (Objects.isNull(key)) {
            key = UUID.randomUUID().toString();
        }
        ObjectMetadata metadata = new ObjectMetadata();
        PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, key, inputStream, metadata);
        PutObjectResult putObjectResult = cosClient.putObject(putObjectRequest);

        System.out.println(JSON.toJSONString(putObjectResult));
        return DOMAIN + key;
    }



}
